package me.zhengjie.modules.system.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import me.zhengjie.modules.system.service.ZabbixApi;
import me.zhengjie.modules.system.service.dto.ZabbixQueryCriteria;
import me.zhengjie.utils.AreacodeContant;
import me.zhengjie.utils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.mapstruct.ap.shaded.freemarker.ext.beans.HashAdapter;
import org.mapstruct.ap.shaded.freemarker.template.utility.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by bruce on 19/7/11.
 */
@RestController
@RequestMapping("web")
public class ZabbixController {

    @Autowired
    private ZabbixApi zabbixApi;

    @GetMapping(value = "/zabbix/hostgroup/get")
    public ResponseEntity hostGroupGet(HttpServletRequest request) {
        HashMap<String,Object> filter = new HashMap<String,Object>();
        filter.put("real_hosts",Boolean.TRUE);

        JSONArray array = zabbixApi.hostGroup_Get(filter);
        JSONArray result = new JSONArray();

        String fullFlag = request.getParameter("flag");

        for(Object obj: array) {
            JSONObject groupItem = new JSONObject();
            groupItem.put("groupid", ((JSONObject)obj).getIntValue("groupid"));
            String name = ((JSONObject)obj).getString("name");
            if(me.zhengjie.utils.StringUtils.isEmpty(fullFlag)) {
                if (name.startsWith("VIP-")) {
                    groupItem.put("name", name.substring(4));
                    result.add(groupItem);
                }
            }else{
                groupItem.put("name",name);
                result.add(groupItem);
            }
        }

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @GetMapping(value = "/zabbix/alarms/get")
    public ResponseEntity CityAlarmsStats(ZabbixQueryCriteria criteria) {
        //获取机器组,包含机器,才有可能关联错误
        HashMap<String,Object> filter = new HashMap<String,Object>();
        filter.put("real_hosts",Boolean.TRUE);

        JSONArray array = zabbixApi.hostGroup_Get(filter);

        HashMap<Integer,String> groupidNameMap = new HashMap<Integer,String>(); //组id对应组名
        for(Object obj: array) {
            groupidNameMap.put( ((JSONObject)obj).getIntValue("groupid"),
                    ((JSONObject)obj).getString("name") );
        }

        //获取错误信息
        filter.clear();
        filter.put("selectHosts","extend");
        filter.put("selectGroups","extend");
        filter.put("filter",JSONObject.parse("{\"value\":1}"));
        if(!StringUtils.isEmpty(criteria.getGroupids()))
            filter.put("groupids",criteria.getGroupids());

        JSONArray result = new JSONArray();
        HashMap<Integer,Integer> areaCount = new HashMap<Integer,Integer>(); //地域对应的错误信息
        if(StringUtils.isEmpty(criteria.getParentCityCode()) || criteria.getParentCityCode().equals("0")) { // 默认取全中国的数据
            array = zabbixApi.trigger_Get(filter);
            for(Object obj: array) { //错误数据
                JSONObject trigger = (JSONObject)obj;
                JSONArray groupArray = trigger.getJSONArray("groups");
                for(Object group: groupArray){
                    String groupname = ((JSONObject)group).getString("name");  //组名
                    Integer areacode = AreacodeContant.getAreacode(groupname);
                    if(areacode!=null) {
                        areaCount.put(areacode,areaCount.getOrDefault(groupname,0)+1); //错误数量
                    }else{
                        if(groupname.equals("VIP-工商银行")) {
                            areaCount.put(330000,areaCount.getOrDefault(groupname,0)+1); //错误数量
                        }
                    }
                }
            }

            //返回结果
            for(HashMap.Entry<Integer,Integer> entry: areaCount.entrySet()) {
                if(entry.getKey()%10000==0) {  //省一级
                    JSONObject obj = new JSONObject();
                    obj.put("cityCode", entry.getKey());
                    obj.put("alarmCount", entry.getValue());
                    result.add(obj);
                }
            }
        } else { //省一级
            Integer parentCitycode = Integer.valueOf(criteria.getParentCityCode());  //省一级的编码
            array = zabbixApi.trigger_Get(filter);
            for(Object obj: array) { //错误数据
                JSONObject trigger = (JSONObject)obj;
                JSONArray groupArray = trigger.getJSONArray("groups");
                for(Object group: groupArray){
                    String groupname = ((JSONObject)group).getString("name");  //组名
                    Integer areacode = AreacodeContant.getAreacode(groupname);
                    if(areacode!=null) {
                        if((areacode/10000)==(parentCitycode/10000))
                            areaCount.put(areacode,areaCount.getOrDefault(groupname,0)+1); //错误数量
                    }else{
                        if(groupname.equals("VIP-工商银行") && parentCitycode==330000) {
                            areaCount.put(330100,areaCount.getOrDefault(groupname,0)+1); //错误数量
                        }
                    }
                }
            }

            //返回结果
            for(HashMap.Entry<Integer,Integer> entry: areaCount.entrySet()) {
                JSONObject obj = new JSONObject();
                obj.put("cityCode", entry.getKey());
                obj.put("alarmCount", entry.getValue());
                result.add(obj);

            }
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }


    @GetMapping(value = "/zabbix/alarms/host")
    public ResponseEntity CityAlarmHostsGet(ZabbixQueryCriteria criteria) {
        HashMap<String,Object> filter = new HashMap<String,Object>();
        filter.put("selectHosts","extend");
        filter.put("filter",JSONObject.parse("{\"value\":1}"));
        if(!StringUtils.isEmpty(criteria.getGroupids())){
            filter.put("groupids",criteria.getGroupids().split(","));
        }
        JSONArray triggerArray = zabbixApi.trigger_Get(filter);

        HashMap<Integer,Integer> hostPriorityMap = new HashMap<Integer,Integer>();

        for(Object _obj: triggerArray) {
            JSONObject object = (JSONObject) _obj;
            JSONArray hostsArray = (JSONArray)object.getJSONArray("hosts");
            if(hostsArray.size()>0) {
                Integer hostid = ((JSONObject)hostsArray.toArray()[0]).getInteger("hostid");
                hostPriorityMap.put(hostid,object.getInteger("priority"));
            }
        }

        filter.clear();
        filter.put("selectInterfaces","extend");
        if(!StringUtils.isEmpty(criteria.getGroupids())){
            filter.put("groupids",criteria.getGroupids().split(","));
        }
        filter.put("selectGroups","extend"); //加组信息
        JSONArray array = zabbixApi.host_Get(filter);  //带ip

        JSONArray result = new JSONArray();
        JSONArray result2 = new JSONArray();
        JSONArray result3 = new JSONArray();
        Integer cityCode= null;

        if(!StringUtils.isEmpty(criteria.getCityCode()))
            cityCode = Integer.valueOf(criteria.getCityCode()) ;  //城市代码

        for(Object _hostObj: array) {
            JSONObject hostObj = (JSONObject) _hostObj;
            JSONObject object = new JSONObject();
            JSONArray groupArray = hostObj.getJSONArray("groups");

            boolean flag = false ;
            for(Object group: groupArray){
                String groupname = ((JSONObject)group).getString("name");  //组名
                Integer areacode = AreacodeContant.getAreacode(groupname);
                if(areacode!=null) {
                    if(areacode.equals(cityCode))
                        flag = true;
                }else{
                    if(groupname.equals("VIP-工商银行") && cityCode.equals(330100)) {
                        flag = true;
                    }
                }
            }
            if(!flag)
                continue ; //特定城市才处理

            object.put("hostname",hostObj.getString("name"));
            JSONArray ipArray = (JSONArray)hostObj.getJSONArray("interfaces");
            if(ipArray.size()>0){
                object.put("ip", ((JSONObject)ipArray.toArray()[0]).getString("ip"));
            }else{
                object.put("ip","");
            }

            Integer priority = hostPriorityMap.get(hostObj.getInteger("hostid"));
            if(priority==null){
                object.put("status",1);
                result.add(object);
            }else{
                if(priority>=4){
                    object.put("status",3);
                    result3.add(object);
                }else{
                    object.put("status",2);
                    result2.add(object);
                }
            }
        }
        for(Object obj: result2){
            result.add(0,obj);
        }
        for(Object obj: result3){
            result.add(0,obj);
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @GetMapping(value = "/zabbix/host/get")
    public ResponseEntity hostGet(ZabbixQueryCriteria criteria) {
        HashMap<String,Object> filter = new HashMap<String,Object>();

        filter.put("selectInterfaces","extend");
        if(!StringUtils.isEmpty(criteria.getGroupids())){
            filter.put("groupids",criteria.getGroupids().split(","));
        }
        filter.put("selectGroups","extend"); //加组信息
        JSONArray array = zabbixApi.host_Get(filter);  //带ip

        JSONArray result = new JSONArray();

        for(Object _hostObj: array) {
            JSONObject hostObj = (JSONObject) _hostObj;
            JSONObject object = new JSONObject();
            object.put("hostname",hostObj.getString("name"));
            object.put("hostid",hostObj.getString("hostid"));
            result.add(object);
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }


    @GetMapping(value = "/zabbix/graph/get")
    public ResponseEntity graphGet(ZabbixQueryCriteria criteria) {
        HashMap<String,Object> filter = new HashMap<String,Object>();

        if(!StringUtils.isEmpty(criteria.getHostids())){
            filter.put("hostids",criteria.getHostids().split(","));
        }
        filter.put("selectHosts","extend"); //加组信息

        JSONArray result = new JSONArray();
        JSONArray array = zabbixApi.graph_get(filter);

        for(Object _hostObj: array) {
            JSONObject hostObj = (JSONObject) _hostObj;
            JSONObject object = new JSONObject();
            object.put("graphname",hostObj.getString("name"));
            object.put("graphid",hostObj.getString("graphid"));
            result.add(object);
        }

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @GetMapping(value = "/zabbix/graph/image")
    public ResponseEntity graphImage(HttpServletRequest request, HttpServletResponse response) {
        Map<String,String> params = new HashMap<String,String>();
        if(!StringUtils.isEmpty(request.getParameter("graphId")))
            params.put("graphId",request.getParameter("graphId"));

        if(StringUtils.isEmpty(request.getParameter("period"))) {
            params.put("period", "86400");
        }else{
            params.put("period",request.getParameter("period"));
        }

        if(StringUtils.isEmpty(request.getParameter("stime"))) {
            params.put("stime", DateUtil.parseDateToStr(new Date(System.currentTimeMillis()-86400*1000),DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS));
        }else{
            params.put("stime",request.getParameter("stime"));
        }


        CloseableHttpResponse res = zabbixApi.graphImage(params);
        try{
            if(res != null) {
                response.setContentType("application/octet-stream");
                ServletOutputStream out = response.getOutputStream();
                InputStream in = res.getEntity().getContent();
                byte[] tmp = new byte[1024];
                int a = -1;
                while ((a = in.read(tmp)) != -1) {
                    out.write(tmp, 0, a);
                }
                out.flush();
                out.close();
                in.close();
            }
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        return ResponseEntity.ok().build();
    }

    @GetMapping(value = "/zabbix/trigger/get")
    public ResponseEntity triggerGet() {
        return new ResponseEntity(zabbixApi.trigger_Get(new HashMap<String,Object>()), HttpStatus.OK);
    }

    @GetMapping(value = "/zabbix/dashboard/hoststat/get")
    public ResponseEntity dashboardHoststatGet() {
        return new ResponseEntity(zabbixApi.dashboard_HoststatGet(new HashMap<String,Object>()), HttpStatus.OK);
    }
}
